package com.nice.iot.monitorapp;

import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.yanzhenjie.andserver.annotation.GetMapping;
import com.yanzhenjie.andserver.annotation.PostMapping;
import com.yanzhenjie.andserver.annotation.RequestBody;
import com.yanzhenjie.andserver.annotation.RestController;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@RestController
public class ServerController {

    public static final String TAG = "ServerController";

    public static String imageStr = "";

    @GetMapping("/")
    public String ping() {
        return "SERVER OK";
    }

    public boolean test = false;

    @PostMapping("/alarm")
    public String login(@RequestBody String str) {
//        JSONObject jsonObject = new JSONObject(str);
        Log.i(TAG, str);
        Report report = JSONObject.parseObject(str, Report.class);

        if ("alarmreport".equals(report.getCmd())) {
            Log.i(TAG, "开始报警");
            Log.i(TAG, report.getImageFile());
            imageStr = report.getImageFile();
            EventBus.getDefault().post(new EventFir(true, ""));
        } else if ("alarmreportend".equals(report.getCmd())) {
            Log.i(TAG, "报警结束");
            EventBus.getDefault().post(new EventFir(false, report.getImageFile()));
        } else if ("heartbeat".equals(report.getCmd())) {
            Log.i(TAG, "心跳");

//            EventBus.getDefault().post(new EventFir(!test, report.getImageFile()));

//            EventBus.getDefault().post(new EventFir(test));
//            test = !test;
        }
//        alarmreport
//                alarmreportend

        new Thread(() -> {
            String body = null;
            try {
                body = post("http://129.204.107.168:8090/renren-fast/zxzl/boli/test/alarm", str);
                Log.i(TAG, "服务器返回 " + body);
            } catch (IOException e) {
                Log.i(TAG, "服务器返回1 " + e.getMessage());
                e.printStackTrace();
            }
        }).start();


        return "ok";
    }


    public static final MediaType JSON = MediaType.get("application/json");

    OkHttpClient client = new OkHttpClient();

    String post(String url, String json) throws IOException {
        Log.i(TAG, "-- " + url);
        Log.i(TAG, "-- " + json);
        okhttp3.RequestBody body = okhttp3.RequestBody.create(json, JSON);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }


}
